package io.renren.modules.ueditor.controller;
import com.alibaba.fastjson.JSON;
import io.renren.modules.uploadfile.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@Transactional
@RequestMapping("statics/libs/ueditor1.4.3/jsp")
public class JSPController {

    @Autowired
    FileStorageService fileStorageService;

    @RequestMapping("/controller")
    public void getConfigInfo(HttpServletRequest request, HttpServletResponse response, String action, MultipartFile upfile) throws IOException {
        if (action.equals("config")) {
            //重定向到配置文件
            response.sendRedirect("/admin/statics/libs/ueditor1.4.3/jsp/config.json");
            return;
        }
        if (action.contains("upload")) {
            //文件上传方法，自己实现一下
            String url = request.getContextPath() + "/fileStorage/" + fileStorageService.save(upfile);

            String fileName = upfile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

            //ueditor要求返回格式
            Map<String, Object> map = new HashMap<>();
            //state成功必须返回SUCCESS
            map.put("state", "SUCCESS");
            //图片地址，/ueditor/jsp/config.json配置中配置的图片前缀为"",所以这里返回完成地址
            map.put("url", url);
            map.put("title", upfile.getOriginalFilename());
            map.put("original", upfile.getOriginalFilename());
            map.put("type", suffix);
            map.put("size", upfile.getSize());

            //返回json
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.append(JSON.toJSONString(map));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }
}
